// UdpServer.hpp
#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"

// 给类型起别名
using func_t = std::function<std::string(const std::string &, const std::string &, uint16_t)>; // C++11

extern Log log;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024; // 接收消息的缓冲区大小

class UdpServer
{
public:
    UdpServer(uint16_t port = defaultport, const std::string &ip = defaultip)
        : _port(port), _ip(ip), _isrunning(false), _sockfd(-1)
    {
    }
    void Init()
    {
        // 1. 创建udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); // AF_INET == PF_INET
        if (_sockfd < 0)
        {
            log(Fatal, "socket create error, errno: %d, err message: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        log(Info, "socket create success, socket: %d", _sockfd);

        // 2.1 定义并设置struct sockaddr_in结构体对象
        struct sockaddr_in local; // 定义在用户栈上
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);                  // 需要保证端口号是网络字节序列，因为该端口号是要给对方发送的
        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 1.string->uint32_t, 2.uint32_t是网络字节序的
        // local.sin_addr.s_addr = INADDR_ANY; // 全0
        // std::cout << local.sin_port << ", " << local.sin_addr.s_addr << std::endl;

        // 2.2 bind socket，绑定端口号，把结构体字段设置进内核
        if (bind(_sockfd, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, errno: %d, err message: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        log(Info, "bind success, errno: %d, err message: %s", errno, strerror(errno));
    }
    void Run(func_t func) // 对代码进行分层，把服务器收到的字符串交给上层传进来的func函数去处理
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                log(Warning, "recvfrom error, errno: %d, err message: %s", errno, strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);

            inbuffer[n] = 0; // 把接收到的报文当字符串来看
            std::string info = inbuffer;
            std::string echo_str = func(info, clientip, clientport);

            sendto(_sockfd, echo_str.c_str(), echo_str.size(), 0, (struct sockaddr *)&client, len);
        }
    }
    ~UdpServer()
    {
        if (_sockfd != -1)
            close(_sockfd);
    }

private:
    int _sockfd;     // 网络文件描述符
    uint16_t _port;  // 这个服务器进程的端口号
    std::string _ip; // 1.用户用的最多的是点分十进制字符串风格的IP地址，2.任意地址bind，_ip=0
    bool _isrunning;
};